# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=embree
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=4.2.0
pkgrel=2
pkgdesc="High Performance Ray Tracing Kernels Intel Corporation (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://www.embree.org/"
license=("spdx:Apache-2.0")
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-tbb")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=(${_realname}-${pkgver}.tar.gz::https://github.com/embree/embree/archive/v${pkgver}.tar.gz
        001-build-fixes.patch
        002-arm64-no-mm-malloc.patch)
sha256sums=('b0479ce688045d17aa63ce6223c84b1cdb5edbf00d7eda71c06b7e64e21f53a0'
            '3e5f251a93a6d8241a200fb311cf069643bcb3375a057216bca062df6e12e61b'
            '8299d40d4ec23ecf034d485e12b56cdba2f4bd626305b978109ebfe1df618302')
prepare() {
  cd ${srcdir}/${_realname}-${pkgver}
  patch -p1 -i ${srcdir}/001-build-fixes.patch

  # no _mm_malloc with clangarm64, so just use _aligned_malloc everywhere
  patch -p1 -i ${srcdir}/002-arm64-no-mm-malloc.patch
}

build() {
  mkdir -p build-${MSYSTEM} && cd build-${MSYSTEM}

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ "${CARCH}" == "x86_64" ]]; then
    extra_config+=("-DEMBREE_ISA_AVX512=ON" "-DEMBREE_MAX_ISA=AVX512SKX")
  else
    extra_config+=("-DEMBREE_ISA_AVX512=OFF")
  fi

  if [[ "${CARCH}" == "aarch64" ]]; then
    extra_config+=("-DEMBREE_ARM=ON")
  else
    extra_config+=("-DEMBREE_ARM=OFF")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe -Wno-dev \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DEMBREE_STATIC_LIB=OFF \
    -DEMBREE_ISPC_SUPPORT=OFF \
    -DEMBREE_STACK_PROTECTOR=ON \
    -DEMBREE_TUTORIALS=OFF \
    -DBUILD_TESTING=OFF \
    ${extra_config[@]} \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  DESTDIR=${pkgdir} ${MINGW_PREFIX}/bin/cmake --install .
  install -Dm644 ${srcdir}/${_realname}-${pkgver}/LICENSE.txt "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
